package com.tedu.weibo.interceptor;

import com.tedu.weibo.pojo.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用于验证用户是否登录的拦截器
 * */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //从session中获取用户名，如果用户名不为空，则放行，否则拦截
        /*
        HttpServletRequest请求对象中提供了一个方法
        getSession()，该方法可以获取到对应当前客户端的会话对象
        * */
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //通过Session获取用户登录信息
        if(user==null){//没有登陆
            response.sendRedirect("/index/html");
            return false;//拦截
        }else {
            return true;//放行
        }

    }
}
